import scrapy
import json
from tqdm import tqdm
from scrapys.wudiSpyder.wudiSpyder.items import SportteryMatchItem, OddsSportteryMatchItem


class SportteryFootballSpider(scrapy.Spider):
    name = "SportteryFootballSpider"
    allowed_domains = ["webapi.sporttery.cn"]
    start_urls = [
        "https://webapi.sporttery.cn/gateway/jc/football/getMatchListV1.qry?clientCode=3001",  # 足球-中国竞猜网页面
    ]

    def parse(self, response):
        print("中国竞彩网》》》》》")
        res = json.loads(response.text)
        # 获取所有的日期比赛
        matchInfoList = res.get("value").get("matchInfoList")
        # 每天的比赛
        for i in tqdm(range(len(matchInfoList))):
            subMatchList = matchInfoList[i].get("subMatchList")
            for j in range(len(subMatchList)):
                m = subMatchList[j]
                matchId = m.get("matchId")
                businessDate = m.get("businessDate")
                homeTeamAbbName = m.get("homeTeamAbbName")
                homeTeamId = m.get("homeTeamId")
                awayTeamAbbName = m.get("awayTeamAbbName")
                awayTeamId = m.get("awayTeamId")
                leagueAbbBackColor = m.get("backColor")
                leagueAbbName = m.get("leagueAbbName")
                matchDate = m.get("matchDate")
                matchNum = m.get("matchNum")
                matchNumStr = m.get("matchNumStr")
                matchStatus = m.get("matchStatus")
                matchTime = m.get("matchTime")
                sellStatus = m.get("sellStatus")

                # 提取基本信息
                match_item = SportteryMatchItem()
                match_item['matchId'] = matchId
                match_item['businessDate'] = businessDate
                match_item['homeTeamAbbName'] = homeTeamAbbName
                match_item['homeTeamId'] = homeTeamId
                match_item['awayTeamAbbName'] = awayTeamAbbName
                match_item['awayTeamId'] = awayTeamId
                match_item['leagueAbbBackColor'] = leagueAbbBackColor
                match_item['leagueAbbName'] = leagueAbbName
                match_item['matchDate'] = matchDate
                match_item['matchNum'] = matchNum
                match_item['matchNumStr'] = matchNumStr
                match_item['matchStatus'] = matchStatus
                match_item['matchTime'] = matchTime
                match_item['sellStatus'] = sellStatus

                # 比赛状态说明，matchStatus= Define，说明有比赛，还没有开盘，
                # 比赛状态说明，matchStatus= Selling，说明有比赛，还已经开盘，
                # 比赛状态说明，sellStatus= 1，说明可以销售了，
                # 比赛状态说明，sellStatus= 2，说明已经停售，比赛已经开始或者其他原因停止
                # 目前没有结束的标准，
                yield match_item
                if sellStatus =='1':
                    # 再次去找奖金数据
                    bonus_page = f"https://webapi.sporttery.cn/gateway/jc/football/getFixedBonusV1.qry?clientCode=3001&matchId={matchId}"
                    yield response.follow(bonus_page, callback=self.parse_other)


    # 处理 胜负彩 停售时间及其他信息
    def parse_other(self, response):

        res = json.loads(response.text)
        v = res.get("value")
        oddsHistory = v.get("oddsHistory")
        matchId = oddsHistory.get("matchId")
        hadList = oddsHistory.get("hadList")
        hhadList = oddsHistory.get("hhadList")
        ttgList = oddsHistory.get("ttgList")
        hafuList = oddsHistory.get("hafuList")
        crsList = oddsHistory.get("crsList")

        singleList = oddsHistory.get("singleList")
        print("获取奖金。。。",matchId)
        spf_s,spf_p,spf_f = 0,0,0
        if hadList:
            had = hadList[-1]
            spf_s = float(had.get("h"))
            spf_p = float(had.get("d"))
            spf_f = float(had.get("a"))
        spf_bonus = "{},{},{}".format(spf_s, spf_p, spf_f)

        rspf_s,rspf_p,rspf_f = 0,0,0
        goalLine = "0"
        if hhadList:
            hhad = hhadList[-1]
            rspf_s = float(hhad.get("h"))
            rspf_p = float(hhad.get("d"))
            rspf_f = float(hhad.get("a"))
            goalLine = hhad.get("goalLine")
        rspf_bonus = "{},{},{}".format(rspf_s, rspf_p, rspf_f)

        ss, sp, sf,ps, pp, pf,fs, fp, ff = 0,0,0,0,0,0,0,0,0
        if hafuList:
            org = hafuList[-1]
            ss = float(org.get("hh"))
            sp = float(org.get("hd"))
            sf = float(org.get("ha"))
            ps = float(org.get("dh"))
            pp = float(org.get("dd"))
            pf = float(org.get("da"))
            fs = float(org.get("ah"))
            fp = float(org.get("ad"))
            ff = float(org.get("aa"))

        bqc_bonus = "{},{},{},{},{},{},{},{},{}".format(ss, sp, sf, ps, pp, pf, fs, fp, ff)

        g0, g1, g2, g3, g4, g5, g6, g7 = 0,0,0,0,0,0,0,0
        if ttgList:
            org = ttgList[-1]
            g0 = float(org.get("s0"))
            g1 = float(org.get("s1"))
            g2 = float(org.get("s2"))
            g3 = float(org.get("s3"))
            g4 = float(org.get("s4"))
            g5 = float(org.get("s5"))
            g6 = float(org.get("s6"))
            g7 = float(org.get("s7"))

        ttg_bonus = "{},{},{},{},{},{},{},{}".format(g0, g1, g2, g3, g4, g5, g6, g7)

        s10, s20, s21, s30, s31, s32, s40, s41, s42, s50, s51, s52, ss = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
        s00,s11, s22, s33, sp = 0,0, 0, 0, 0
        s01, s02, s12, s03, s13, s23, s04, s14, s24, s05, s15, s25, sf = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
        if crsList:
            crs = crsList[-1]
            s10, s20, s21 = crs.get("s01s00"), crs.get("s02s00"), crs.get("s02s01")
            s30, s31, s32 = crs.get("s03s00"), crs.get("s03s01"), crs.get("s03s02"),
            s40, s41, s42 = crs.get("s04s00"), crs.get("s04s01"), crs.get("s04s02")
            s50, s51, s52, ss = crs.get("s05s00"), crs.get("s05s01"), crs.get("s05s00"), crs.get("s-1sh")

            s00,s11, s22, s33, sp = crs.get("s00s00"),crs.get("s01s01"), crs.get("s02s02"), crs.get("s03s03"), crs.get("s-1sd")

            s01, s02, s12 = crs.get("s00s01"), crs.get("s00s02"), crs.get("s01s02")
            s03, s13, s23= crs.get("s00s03"), crs.get("s01s03"), crs.get("s02s03"),
            s04, s14, s24 = crs.get("s00s04"), crs.get("s01s04"), crs.get("s02s04")
            s05, s15, s25, sf = crs.get("s00s05"), crs.get("s01s05"), crs.get("s02s05"), crs.get("s-1sa")

        s_b = f"{s10}, {s20}, {s21}, {s30}, {s31}, {s32}, {s40}, {s41}, {s42}, {s50}, {s51}, {s52}, {ss}"
        s_p = f"{s00},{s11}, {s22}, {s33}, {sp}"
        s_f = f"{s01}, {s02}, {s12}, {s03}, {s13}, {s23}, {s04}, {s14}, {s24}, {s05}, {s15}, {s25}, {sf}"

        crs_bonus = f"{s_b},{s_p},{s_f}"

        # 是否单关解析
        spf_single = 0
        rspf_single = 0
        spf_single_list = list(filter(lambda x: x["poolCode"] == 'HAD', singleList))
        if spf_single_list:
            spf_single = spf_single_list[0]["single"]

        rspf_single_list = list(filter(lambda x: x["poolCode"] == 'HHAD', singleList))
        if rspf_single_list:
            rspf_single = rspf_single_list[0]["single"]

        # 再把原始的奖金数据及开奖数据保存到数据库里面
        sectionsNo999 = v.get("sectionsNo999")
        singleList = oddsHistory.get("singleList")
        crsList = oddsHistory.get("crsList")
        hadList = oddsHistory.get("hadList")
        hafuList = oddsHistory.get("hafuList")
        hhadList = oddsHistory.get("hhadList")
        ttgList = oddsHistory.get("ttgList")



        # 保存奖金指数
        odd_item = OddsSportteryMatchItem()
        odd_item["matchId"] = matchId
        odd_item["spf_bonus"] = spf_bonus
        odd_item["rspf_bonus"] = rspf_bonus
        odd_item["ttg_bonus"] = ttg_bonus
        odd_item["bqc_bonus"] = bqc_bonus
        odd_item["crs_bonus"] = crs_bonus
        odd_item["spf_single"] = spf_single
        odd_item["rspf_single"] = rspf_single
        odd_item["goalLine"] = goalLine

        odd_item["sectionsNo999"] = sectionsNo999
        odd_item["singleList"] = singleList
        odd_item["crsList"] = crsList
        odd_item["hadList"] = hadList
        odd_item["hafuList"] = hafuList
        odd_item["hhadList"] = hhadList
        odd_item["ttgList"] = ttgList

        yield odd_item
